package com.joeshing.security.service;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.stereotype.Service;

/**
 * @author chencx
 * @date 2012-9-3
 * 
 */
@Service
public class LoginAuthenticationImpl implements LoginAuthentication {

	@Autowired
	@Qualifier("org.springframework.security.authenticationManager")
	protected AuthenticationManager authenticationManager;

	// @Resource
	// private QqAuthenticationProvider authenticationProvider;

	private final Logger logger = Logger.getLogger(this.getClass());

	public void authentication(HttpServletRequest request, String account, String password) {
		logger.debug("do Authentication Account: " + account);
		UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(account, password);
		request.getSession();
		try {

			token.setDetails(new WebAuthenticationDetails(request));
			Authentication result = authenticationManager.authenticate(token);
			// Authentication result = new
			// UsernamePasswordAuthenticationToken(memUser.getSysUser().getUserAccount(),
			// memUser.getSysUser().getUserPwd(), AUTHORITIES);
			SecurityContextHolder.getContext().setAuthentication(result);
			request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
					SecurityContextHolder.getContext());
		} catch (AuthenticationException e) {
			logger.error("Authentication failed: Account(" + account + ") & PWD (" + password + "): " + e.getMessage());
		}
	}
}
